﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Application.SystemManage;
using YunSpace.Core;
using YunSpace.Data;
using YunSpace.Domain.Entity.OrderFlowManage;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Domain.IRepository.OrderFlowManage;
using YunSpace.Domain.IRepository.OrderMgr;
using YunSpace.Domain.IRepository.SiteMgr;
using YunSpace.Domain.IRepository.SystemManage;
using YunSpace.Domain.ViewModel.SiteMgr;
using YunSpace.Domain.ViewModel.ClientManager;
using YunSpace.Repository.MiniSite;
using YunSpace.Repository.OrderFlowManage;
using YunSpace.Repository.OrderMgr;
using YunSpace.Repository.SiteMgr;
using YunSpace.Repository.SystemManage;
using YunSpace.Domain.ViewModel.System;

namespace YunSpace.Application.SiteMgr
{
    public class ClientInfosApp
    {
        private ItemsDetailApp itemsDetailApp = new ItemsDetailApp();
        private SysAutoApp autoApp = new SysAutoApp();
        ISiteClientsRepository clientRepository = new SiteClientsRepository();
        ISiteClientsAllProjectsRepository projectsRepository = new SiteClientsAllProjectsRepository();
        ISiteClientsProjectByContactRepository contactRepository = new SiteClientsProjectByContactRepository();
        ISiteClientsProjectByDemandRepository demandRepository = new SiteClientsProjectByDemandRepository();
        ISiteClientsServiceMappingRepository serviceRepository = new SiteClientsServiceMappingRepository();
        ISiteClientsBrandsEntityRepository brandsRepository = new SiteClientsBrandsEntityRepository();
        IClientOrderrecommendRepository clientOrderrecommendRepository = new ClientOrderrecommendRepository();

        IOrderRepository orderRepository = new OrderRepository();
        IAreaRepository areaRepository = new AreaRepository();

        public List<ClientHistoryOrderActionModel> GetClientHistoryOrderList(Pagination pagination, string queryJson)
        {
            List<ClientHistoryOrderActionModel> result = new List<ClientHistoryOrderActionModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,b.F_Source,e.F_ClientName,b.F_ActivityTheme,b.F_ActivityType,b.F_DemandCash,DATE_FORMAT(b.F_ActivityStartDate,'%Y-%m-%d') F_ActivityStartDate,DATE_FORMAT(b.F_ActivityEndDate,'%Y-%m-%d') F_ActivityEndDate,b.F_ActivityCityId,a.F_OrderState,a.F_OrderStateProcess,f.F_RealName F_FlowUser,g.F_RealName F_OldFlowUser,a.F_CreatorTime from Site_Client_Order a 
                                inner join Site_Clients_ProjectByDemand b on a.F_DemandId=b.F_Id
                                left join Site_Clients_AllProjectsMapping scl on b.F_Id=scl.F_DemandId
                                left join Site_Clients_AllProjects c on scl.F_ProjectId=c.F_Id
                                left join Site_Clients_ContactMapping scc on scc.F_DemandId=b.F_Id
                                left join Site_Clients_ProjectByContact d on d.F_Id=scc.F_ContactId                               
                                left join Site_Clients e on c.F_ClientId=e.F_Id
                                inner join Sys_User f on a.F_FlowUserId=f.F_Id
                                left join Sys_User g on a.F_OldFlowUserId=g.F_Id where e.F_Id=@F_ClientId";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", queryParam["F_ClientId"])
                };
                result = db.FindList<ClientHistoryOrderActionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        /// <summary>
        /// 获取所有的客户信息
        /// </summary>
        /// <returns></returns>
        public List<SiteClientsEntity> GetClients()
        {
            List<SiteClientsEntity> clientList = CacheFactory.Cache().Get("KHXX") as List<SiteClientsEntity>;
            if (clientList == null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var strSql = @"select *  from Site_Clients where F_ClientName is not null";
                    clientList = db.FindList<SiteClientsEntity>(strSql);
                    CacheFactory.Cache().Insert("KHXX", clientList);
                }
            }
            return clientList;
        }

        public List<SiteClientsBrandsEntity> GetBrands()
        {
            List<SiteClientsBrandsEntity> brandsList = CacheFactory.Cache().Get("PPXX") as List<SiteClientsBrandsEntity>;
            if (brandsList == null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var strSql = @"select *  from Site_Clients_Brands a where a.F_BrandName is not null";
                    brandsList = db.FindList<SiteClientsBrandsEntity>(strSql);
                    CacheFactory.Cache().Insert("PPXX", brandsList);
                }
            }
            return brandsList;
        }

        public List<UserEntity> GetUsers() {
            List<UserEntity> result = CacheFactory.Cache().Get("User") as List<UserEntity>;
            if (result == null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var strSql = @"select * from  Sys_User a";
                    result = db.FindList<UserEntity>(strSql);
                    CacheFactory.Cache().Insert("User", result);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取所有的服务商数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public List<ClientServiceInfoActionModel> GetClientServiceInfoList(Pagination pagination, string queryJson)
        {
            List<ClientServiceInfoActionModel> result = new List<ClientServiceInfoActionModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select cl.F_Id,cl.F_ClientType,cl.F_ClientName,cl.F_CompanyType,cl.F_CityId,cl.F_ClientLevel,a.F_ProjectName,b.F_ActivityTheme,b.F_ActivityType,b.F_DemandCash,DATE_FORMAT(b.F_ActivityStartDate,'%Y-%m-%d') F_ActivityStartDate,DATE_FORMAT(b.F_ActivityEndDate,'%Y-%m-%d') F_ActivityEndDate,b.F_ActivityCityId,c.F_Contact,c.F_Phone,d.F_RealName,b.F_CreatorTime 
                                from Site_Clients cl 
                                inner join Site_Clients_ProjectByDemand b on cl.F_Id=b.F_ClientId
                                left join Site_Clients_AllProjectsMapping e on e.F_DemandId=b.F_Id
                                left join Site_Clients_AllProjects a on a.F_Id=e.F_ProjectId
                                left join Site_Clients_ContactMapping f on f.F_DemandId=b.F_Id
                                left join Site_Clients_ProjectByContact c on c.F_Id=f.F_ContactId
                                inner join Sys_User d on b.F_CreatorUserId=d.F_Id 
                                where cl.F_Id in(
                                select a.F_ServiceId from Site_Clients cl
                                inner join Site_Clients_ServiceMapping a on cl.F_Id=a.F_ClientId where cl.F_Id=@F_ClientId)";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", queryParam["F_ClientId"])
                };
                result = db.FindList<ClientServiceInfoActionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        /// <summary>
        /// 获取客户项目组信息
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public List<ClientProjectInfoActionModel> GetClientProjectInfoList(Pagination pagination, string queryJson)
        {
            List<ClientProjectInfoActionModel> result = new List<ClientProjectInfoActionModel>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                var strSql = @"select d.F_Id,b.F_Id DemandId,a.F_ClientType,a.F_ClientName,f.F_BrandName,d.F_ProjectName,b.F_Source,b.F_ActivityTheme,b.F_ActivityType,b.F_DemandCash,
                                DATE_FORMAT(b.F_ActivityStartDate,'%Y-%m-%d') F_ActivityStartDate,DATE_FORMAT(b.F_ActivityEndDate,'%Y-%m-%d') F_ActivityEndDate,b.F_ActivityCityId,
                                h.F_Contact,h.F_Phone,b.F_CreatorTime,j.F_RealName from Site_Clients a
                                inner join Site_Clients_ProjectByDemand b on a.F_Id=b.F_ClientId
                                left join Site_Clients_AllProjectsMapping c on c.F_DemandId=b.F_Id
                                left join Site_Clients_AllProjects d on c.F_ProjectId=d.F_Id
                                left join Site_Clients_BrandsMapping e on e.F_DemandId=b.F_Id
                                left join Site_Clients_Brands f on e.F_BrandId =f.F_Id
                                left join Site_Clients_ContactMapping g on g.F_DemandId=b.F_Id
                                left join Site_Clients_ProjectByContact h on h.F_Id=g.F_ContactId
                                inner join Sys_User j on b.F_CreatorUserId=j.F_Id 
                                where 1=1 {0} {1} {2} {3}";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", queryParam["F_ClientId"]),
                    new MySqlParameter("@F_CreatorUserId", queryParam["F_CreatorUserId"]),
                    new MySqlParameter("@F_ProjectId", queryParam["F_ProjectId"]),
                    new MySqlParameter("@F_BrandId", queryParam["F_BrandId"])
                };
                strSql = string.Format(strSql, queryParam["F_ClientId"].IsEmpty() ? "" : " and b.F_ClientId=@F_ClientId", 
                    queryParam["F_CreatorUserId"].IsEmpty() ? "" : " and b.F_CreatorUserId=@F_CreatorUserId",
                    queryParam["F_ProjectId"].IsEmpty()?"": " and d.F_Id=@F_ProjectId",
                    queryParam["F_BrandId"].IsEmpty() ? "" : " and f.F_Id=@F_BrandId"
                    );
                result = db.FindList<ClientProjectInfoActionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        /// <summary>
        /// 获取客户的关联数据列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public List<ClientInfosManagerActionModel> GetClientsList(Pagination pagination, string queryJson, string userId)
        {
            var result = new List<ClientInfosManagerActionModel>();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select a.F_Id,a.F_ClientName,a.F_ClientType,a.F_CityId,a.F_AreaId,a.F_Address,a.F_IndustryId,a.F_ClientLevel,b.F_ActivityTheme,b.F_ActivityType,
                                d.F_ProjectName,d.F_Id projectId,f.F_BrandName,f.F_Id brandId,u.F_RealName,b.F_CreatorUserId from  Site_Clients a 
                                inner join Site_Clients_ProjectByDemand b on a.F_Id=b.F_ClientId
                                inner join Sys_User u on b.F_CreatorUserId=u.F_Id {7}
                                left join Site_Clients_AllProjectsMapping c on c.F_DemandId=b.F_Id
                                left join Site_Clients_AllProjects d on d.F_Id=c.F_ProjectId
                                left join Site_Clients_BrandsMapping e on e.F_DemandId=b.F_Id
                                left join Site_Clients_Brands f on f.F_Id=e.F_BrandId                                
                                where 1=1 {0} {1} {2} {3} {4} {5} {6} order by b.F_CreatorTime desc,b.F_CreatorUserId desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", queryParam["F_ClientId"]),
                    new MySqlParameter("@F_CityId", queryParam["F_CityId"]),
                    new MySqlParameter("@F_ClientType", queryParam["F_ClientType"]),
                    new MySqlParameter("@F_IndustryId", queryParam["F_IndustryId"]),                   
                    new MySqlParameter("@F_CreatorUserId", userId),
                    new MySqlParameter("@F_UserId", queryParam["F_UserId"]),
                };

                ///获取用户权限
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                RoleApp role = new RoleApp();
                RoleEntity roleEntity= role.GetForm(LoginInfo.RoleId);
                OrganizeApp organize = new OrganizeApp();
                OrganizeEntity organizeEntity = organize.GetForm(LoginInfo.DepartmentId);
                
                string F_GroupId = "";
                if (roleEntity.F_EnCode == "1006" || roleEntity.F_EnCode == "1012")
                {
                    F_GroupId += " and u.F_GroupId='" + LoginInfo.F_GroupId + "'";
                }
                else if (roleEntity.F_EnCode == "1004") {
                    F_GroupId += " and u.F_GroupId='" + LoginInfo.F_GroupId + "' and u.F_Id='"+ LoginInfo.F_GroupId + "'";
                }

                strSql = string.Format(strSql,
                    queryParam["F_ClientId"].IsEmpty() ? "" : " and a.F_Id=@F_ClientId",
                    queryParam["F_CityId"].IsEmpty() ? "" : " and a.F_CityId=@F_CityId",
                    queryParam["F_ClientType"].IsEmpty() ? "" : " and a.F_ClientType=@F_ClientType",
                    queryParam["F_IndustryId"].IsEmpty() ? "" : " and a.F_IndustryId=@F_IndustryId",
                    "",                  
                    userId.IsEmpty() ? "" : " ",
                    queryParam["F_UserId"].IsEmpty() ? "" : " and b.F_CreatorUserId=@F_UserId",                    
                    F_GroupId
                    );
                result = db.FindList<ClientInfosManagerActionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        /// <summary>
        /// 获取客户的关联数据列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public List<ClientInfosManagerActionModel> GetMyClientsList(Pagination pagination, string queryJson, string userId)
        {
            var result = new List<ClientInfosManagerActionModel>();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select distinct a.F_Id,a.F_ClientName,a.F_ClientType,a.F_CityId,a.F_AreaId,a.F_Address,a.F_IndustryId,a.F_ClientLevel,
                                d.F_ProjectName,f.F_BrandName,u.F_RealName,d.F_Id projectId,f.F_Id brandId,b.F_CreatorUserId from  Site_Clients a 
                                inner join Site_Clients_ProjectByDemand b on a.F_Id=b.F_ClientId
                                left join Site_Clients_AllProjectsMapping c on c.F_DemandId=b.F_Id
                                left join Site_Clients_AllProjects d on d.F_Id=c.F_ProjectId
                                left join Site_Clients_BrandsMapping e on e.F_DemandId=b.F_Id
                                left join Site_Clients_Brands f on f.F_Id=e.F_BrandId
                                left join Sys_User u on b.F_CreatorUserId=u.F_Id
                                where 1=1 {0} {1} {2} {3} {4} {5} {6} {7} order by b.F_CreatorTime desc,b.F_CreatorUserId desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", queryParam["F_ClientId"]),
                    new MySqlParameter("@F_CityId", queryParam["F_CityId"]),
                    new MySqlParameter("@F_ClientType", queryParam["F_ClientType"]),
                    new MySqlParameter("@F_IndustryId", queryParam["F_IndustryId"]),
                    //new MySqlParameter("@F_DemandCash", queryParam["F_DemandCash"]),
                    new MySqlParameter("@F_CreatorUserId", userId),
                    new MySqlParameter("@F_ProjectId", queryParam["F_ProjectId"]),
                    new MySqlParameter("@F_BrandId", queryParam["F_BrandId"]),
                };
                strSql = string.Format(strSql,
                    queryParam["F_ClientId"].IsEmpty() ? "" : " and a.F_Id=@F_ClientId",
                    queryParam["F_CityId"].IsEmpty() ? "" : " and a.F_CityId=@F_CityId",
                    queryParam["F_ClientType"].IsEmpty() ? "" : " and a.F_ClientType=@F_ClientType",
                    queryParam["F_IndustryId"].IsEmpty() ? "" : " and a.F_IndustryId=@F_IndustryId",
                    "",
                    //queryParam["F_DemandCash"].IsEmpty() ? "" : " and e.F_DemandCash>=@F_DemandCash",
                    userId.IsEmpty() ? "" : " and b.F_CreatorUserId=@F_CreatorUserId",
                    queryParam["F_ProjectId"].IsEmpty() ? "" : " and d.F_Id=@F_ProjectId",
                    queryParam["F_BrandId"].IsEmpty() ? "" : " and f.F_Id=@F_BrandId"
                    );
                result = db.FindList<ClientInfosManagerActionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        /// <summary>
        /// 通过项目编号获取其联系人信息
        /// </summary>
        /// <param name="F_Id"></param>
        /// <returns></returns>
        public List<SiteClientsProjectByContactEntity> GetProjectInfo(string F_Id)
        {
            List<SiteClientsProjectByContactEntity> contacts = new List<SiteClientsProjectByContactEntity>();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Clients_ProjectByContact a where a.F_ProjectId=@F_ProjectId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ProjectId", F_Id),
                };
                contacts = db.FindList<SiteClientsProjectByContactEntity>(strSql, parameter);
            }
            return contacts;
        }

        public SiteClientsEntity GetClientEntity(string F_ClientId)
        {
            SiteClientsEntity result = new SiteClientsEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Clients a where a.F_Id=@F_ClientId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", F_ClientId),
                };
                result = db.FindList<SiteClientsEntity>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public List<ClientProjectUpdateActionModel> GetProjectInfoList(Pagination pagination, string F_ClientId,string F_UserId)
        {
            List<ClientProjectUpdateActionModel> result = new List<ClientProjectUpdateActionModel>();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select c.F_Id,c.F_Id as DemandId,c.F_ClientId,d.F_Id F_BrandId,a.F_Id F_ProjectId,d.F_BrandName,a.F_ProjectName,
                                b.F_Id contactId,b.F_Contact,b.F_DepartmentId,b.F_PositionId,b.F_Sex,b.F_Phone,b.F_Telephone,b.F_Mail,c.F_ActivityTheme,
                                c.F_ActivityType,c.F_DemandCash, DATE_FORMAT(c.F_ActivityStartDate,'%Y-%m-%d') F_ActivityStartDate 
                                , DATE_FORMAT(c.F_BuildDate,'%Y-%m-%d') F_BuildDate,DATE_FORMAT(c.F_ActivityEndDate,'%Y-%m-%d') F_ActivityEndDate,
                                c.F_ActivityCityId,c.F_SiteType,c.F_SiteArea 
                                from Site_Clients_ProjectByDemand c
								left join Site_Clients_AllProjectsMapping sca on sca.F_DemandId=c.F_Id
								left join Site_Clients_AllProjects a on a.F_Id=sca.F_ProjectId
								left join Site_Clients_ContactMapping scc on scc.F_DemandId=c.F_Id
								left join Site_Clients_ProjectByContact b on b.F_Id=scc.F_ContactId
								left join Site_Clients_BrandsMapping scb on scb.F_DemandId=c.F_Id
								left join Site_Clients_Brands d on d.F_Id=scb.F_BrandId
                                where c.F_ClientId=@F_ClientId and c.F_CreatorUserId=@F_UserId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", F_ClientId),
                    new MySqlParameter("@F_UserId", F_UserId),
                };
                result = db.FindList<ClientProjectUpdateActionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        public ClientProjectUpdateActionModel GetProjectInfoDetail(string DemandId)
        {
            ClientProjectUpdateActionModel result = new ClientProjectUpdateActionModel();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select a.F_Id,c.F_Id as DemandId,a.F_Id F_ProjectId,c.F_Source,j.F_BrandName,j.F_Id F_BrandId,d.F_ClientType,b.F_Id as contactId,d.F_Id F_ClientId,
                                d.F_ClientName,d.F_IndustryId,a.F_ProjectName,b.F_Contact,b.F_DepartmentId,b.F_PositionId,b.F_Sex,b.F_Phone,b.F_Telephone,b.F_Mail,
                                c.F_ActivityTheme,c.F_ActivityType,c.F_DemandCash,c.F_ActivityStartDate,c.F_BuildDate
                                ,c.F_ActivityEndDate,c.F_Intention,c.F_ActivityCityId,c.F_SiteType,c.F_PersionNumber,c.F_SiteArea,c.F_Height,c.F_Note,
                                k.F_Id F_MappingId,k.F_ClientName MappingName,c.F_IndustryId F_ZkIndustryId
                                from Site_Clients_ProjectByDemand c 
							    left join Site_Clients_AllProjectsMapping sca on sca.F_DemandId=c.F_Id
							    left join Site_Clients_AllProjects a on sca.F_ProjectId=a.F_Id
							    left join Site_Clients_ContactMapping scc on scc.F_DemandId=c.F_Id
								left join Site_Clients_ProjectByContact b on b.F_Id=scc.F_ContactId										                                 
                                left join Site_Clients_BrandsMapping h on h.F_DemandId=c.F_Id
								left join Site_Clients_Brands j on j.F_Id=h.F_BrandId                               
                                left join Site_Clients d on a.F_ClientId=d.F_Id 
                                left join (select f.F_ServiceId,g.F_Id,g.F_ClientName,g.F_IndustryId from Site_Clients_ServiceMapping f 
								inner join Site_Clients g on f.F_ClientId=g.F_Id group by f.F_ServiceId,g.F_Id,g.F_ClientName,g.F_IndustryId) k 
								on d.F_Id=k.F_ServiceId
                                where c.F_Id=@DemandId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@DemandId", DemandId),
                };
                result = db.FindList<ClientProjectUpdateActionModel>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public List<SiteClientsAllProjectsEntity> GetProjectList(string F_ClientId)
        {
            List<SiteClientsAllProjectsEntity> result = CacheFactory.Cache().Get("XMZXX") as List<SiteClientsAllProjectsEntity>;
            var pp = from p in result where p.F_ClientId.Equals(F_ClientId) select p;
            return pp.ToList<SiteClientsAllProjectsEntity>();
        }

        /// <summary>
        /// 获取所有的项目组信息
        /// </summary>
        /// <returns></returns>
        public List<SiteClientsAllProjectsEntity> GetClientsAllProjects()
        {
            List<SiteClientsAllProjectsEntity> projects = CacheFactory.Cache().Get("XMZXX") as List<SiteClientsAllProjectsEntity>;
            if (projects == null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var strSql = @"select *  from Site_Clients_AllProjects a where a.F_ProjectName is not null";
                    projects = db.FindList<SiteClientsAllProjectsEntity>(strSql);
                    CacheFactory.Cache().Insert("XMZXX", projects);
                }
            }
            return projects;
        }

        /// <summary>
        /// 获取所有的联系人信息
        /// </summary>
        /// <returns></returns>
        public List<SiteClientsProjectByContactEntity> GetClientsContacts()
        {
            List<SiteClientsProjectByContactEntity> contacts = CacheFactory.Cache().Get("LXRXX") as List<SiteClientsProjectByContactEntity>;
            if (contacts == null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var strSql = @"select *  from Site_Clients_ProjectByContact a where a.F_Contact is not null";
                    contacts = db.FindList<SiteClientsProjectByContactEntity>(strSql);
                    CacheFactory.Cache().Insert("LXRXX", contacts);
                }
            }
            return contacts;
        }

        public List<ItemsDetailActionModel> GetItemList(string enCode)
        {
            return itemsDetailApp.GetItemList(enCode);
        }

        public List<AreaModel> GetAllCitys() {
            List<AreaModel> citys = CacheFactory.Cache().Get("City") as List<AreaModel>;
            if (citys == null)
            {
                using (var db = new RepositoryBase())
                {
                    string strSql = @"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName  from Sys_Area a where a.F_Layers=2";
                    citys = db.FindList<AreaModel>(strSql);
                    CacheFactory.Cache().Insert("City", citys);
                }
            }      
            return citys;
        }

        public List<AreaModel> GetAllAreas()
        {
            List<AreaModel> citys = CacheFactory.Cache().Get("Area") as List<AreaModel>;
            if (citys == null)
            {
                using (var db = new RepositoryBase())
                {
                    string strSql = @"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName  from Sys_Area a where a.F_Layers=3";
                    citys = db.FindList<AreaModel>(strSql);
                    CacheFactory.Cache().Insert("Area", citys);
                }
            }
            return citys;
        }

        /// <summary>
        /// 商圈
        /// </summary>
        public List<AreaModel> GetAllBusinessAreas()
        {
            List<AreaModel> citys = CacheFactory.Cache().Get("BusinessArea") as List<AreaModel>;
            if (citys == null)
            {
                using (var db = new RepositoryBase())
                {
                    string strSql = @"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName  from Sys_Area a where a.F_Layers=4";
                    citys = db.FindList<AreaModel>(strSql);
                    CacheFactory.Cache().Insert("Area", citys);
                }
            }
            return citys;
        }

        /// <summary>
        /// 获取所有城市信息
        /// </summary>
        /// <returns></returns>
        public List<AreaEntity> GetCitys()
        {
            List<AreaEntity> cityList = new List<AreaEntity>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                var strSql = @"select *  from Sys_Area";
                cityList = db.FindList<AreaEntity>(strSql);
            }
            return cityList;
        }

        /// <summary>
        /// 查询是否存在客户和服务商映射关系
        /// </summary>
        /// <param name="F_ClientId"></param>
        /// <param name="F_ServiceId"></param>
        /// <returns></returns>
        public SiteClientsServiceMappingEntity GetFindServiceMapping(string F_ClientId, string F_ServiceId)
        {
            SiteClientsServiceMappingEntity serviceEntity = new SiteClientsServiceMappingEntity();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select * from Site_Clients_ServiceMapping a where a.F_ClientId=@F_ClientId and a.F_ServiceId=@F_ServiceId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ClientId", F_ClientId),
                    new MySqlParameter("@F_ServiceId", F_ServiceId)
                };
                serviceEntity = db.FindList<SiteClientsServiceMappingEntity>(strSql, parameter).FirstOrDefault();
            }
            return serviceEntity;
        }

        public SiteClientsBrandsMappingEntity GetFindBrandsMappingEntity(string F_BrandId, string F_DemandId)
        {
            SiteClientsBrandsMappingEntity result = new SiteClientsBrandsMappingEntity();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select * from Site_Clients_BrandsMapping a where a.F_BrandId=@F_BrandId and a.F_DemandId=@F_DemandId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_BrandId", F_BrandId),
                    new MySqlParameter("@F_DemandId", F_DemandId)
                };
                result = db.FindList<SiteClientsBrandsMappingEntity>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public SiteClientsAllProjectsMappingEntity GetSiteClientsAllProjectsMapping(string projectId, string F_DemandId)
        {
            SiteClientsAllProjectsMappingEntity result = new SiteClientsAllProjectsMappingEntity();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select * from Site_Clients_AllProjectsMapping a where a.F_ProjectId=@F_ProjectId and a.F_DemandId=@F_DemandId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ProjectId", projectId),
                    new MySqlParameter("@F_DemandId", F_DemandId)
                };
                result = db.FindList<SiteClientsAllProjectsMappingEntity>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public SiteClientsContactMappingEntity GetSiteClientsContactMapping(string F_ContactId, string F_DemandId)
        {
            SiteClientsContactMappingEntity result = new SiteClientsContactMappingEntity();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select * from Site_Clients_ContactMapping a where a.F_ContactId=@F_ContactId and a.F_DemandId=@F_DemandId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ContactId", F_ContactId),
                    new MySqlParameter("@F_DemandId", F_DemandId)
                };
                result = db.FindList<SiteClientsContactMappingEntity>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public SiteClientsProjectByContactEntity GetContactInfo(string F_ContactId)
        {
            List<SiteClientsProjectByContactEntity> contacts = CacheFactory.Cache().Get("LXRXX") as List<SiteClientsProjectByContactEntity>;
            var result = from p in contacts where p.F_Id.Equals(F_ContactId) select p;
            return result.ToList<SiteClientsProjectByContactEntity>().FirstOrDefault();
        }

        /// <summary>
        /// 添加客户信息
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="keyValue"></param>
        public ClientDemandSaveModel SubmitForm(ClientTotalActionModel entity, string keyValue)
        {
            ClientDemandSaveModel returnEntity = new ClientDemandSaveModel();
            ClientOrderEntity order = new ClientOrderEntity();
            using (var db = new RepositoryBase().BeginTrans())
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    // 客户信息
                    SiteClientsEntity clientEntity = clientRepository.FindEntity(entity.F_ClientId);
                    if (clientEntity == null)
                    {
                        clientEntity = new SiteClientsEntity();
                        clientEntity.Create();
                        clientEntity.F_ClientType = entity.F_ClientType;
                        clientEntity.F_ClientName = entity.F_ClientId;
                        clientEntity.F_CityId = entity.F_CityId;
                        clientEntity.F_AreaId = entity.F_AreaId;
                        clientEntity.F_Address = entity.F_Address;
                        clientEntity.F_IndustryId = entity.F_IndustryId;
                        clientEntity.F_ClientLevel = entity.F_ClientLevel;
                        db.Insert<SiteClientsEntity>(clientEntity);

                        //操作记录
                        SysOperationLogEntity operation9 = new SysOperationLogEntity();
                        operation9.Create();
                        operation9.F_Flag = 1;
                        operation9.F_Entity = "SiteClientsEntity";
                        operation9.F_Context = clientEntity.ToJson();
                        db.Insert<SysOperationLogEntity>(operation9);

                        List<SiteClientsEntity> clientList = CacheFactory.Cache().Get("KHXX") as List<SiteClientsEntity>;
                        if (clientList == null)
                        {
                            clientList = new List<SiteClientsEntity>();
                        }
                        clientList.Add(clientEntity);
                        CacheFactory.Cache().Insert("KHXX", clientList);
                    }
                    else
                    {
                        clientEntity.F_ClientType = entity.F_ClientType;
                        clientEntity.F_CityId = entity.F_CityId;
                        clientEntity.F_AreaId = entity.F_AreaId;
                        clientEntity.F_Address = entity.F_Address;
                        clientEntity.F_IndustryId = entity.F_IndustryId;
                        clientEntity.F_ClientLevel = entity.F_ClientLevel;
                        db.Update<SiteClientsEntity>(clientEntity);

                        //操作记录
                        SysOperationLogEntity operation8 = new SysOperationLogEntity();
                        operation8.Create();
                        operation8.F_Flag = 2;
                        operation8.F_Entity = "SiteClientsEntity";
                        operation8.F_Context = clientEntity.ToJson();
                        db.Insert<SysOperationLogEntity>(operation8);
                    }

                    // 需求信息
                    SiteClientsProjectByDemandEntity demandEntity = new SiteClientsProjectByDemandEntity();
                    demandEntity.Create();
                    demandEntity.F_Source = entity.F_Source;
                    demandEntity.F_ActivityTheme = entity.F_ActivityTheme;
                    demandEntity.F_ActivityType = entity.F_ActivityType;
                    demandEntity.F_DemandCash = entity.F_DemandCash;
                    demandEntity.F_ActivityStartDate = entity.F_ActivityStartDate;

                    demandEntity.F_ActivityEndDate = entity.F_ActivityEndDate;
                    demandEntity.F_ActivityCityId = entity.F_ActivityCityId;
                    demandEntity.F_SiteType = entity.F_SiteType;
                    demandEntity.F_SiteArea = entity.F_SiteArea;
                    demandEntity.F_Height = entity.F_Height;

                    demandEntity.F_PersionNumber = entity.F_PersionNumber;
                    demandEntity.F_Note = entity.F_Note;
                    demandEntity.F_ClientId = clientEntity.F_Id;
                    demandEntity.F_BuildDate = entity.F_BuildDate;
                    demandEntity.F_IndustryId = entity.F_ZkIndustryId;

                    //检索直客信息
                    if (entity.F_ClientType == "2")
                    {
                        SiteClientsEntity client = clientRepository.FindEntity(entity.F_MappingId);
                        if (client == null && entity.F_MappingId!=null)
                        {
                            client = new SiteClientsEntity();
                            client.Create();
                            client.F_ClientName = entity.F_MappingId;                            
                            db.Insert<SiteClientsEntity>(client);
                            //操作记录
                            SysOperationLogEntity operation7 = new SysOperationLogEntity();
                            operation7.Create();
                            operation7.F_Flag = 1;
                            operation7.F_Entity = "SiteClientsEntity";
                            operation7.F_Context = client.ToJson();
                            db.Insert<SysOperationLogEntity>(operation7);

                            SiteClientsServiceMappingEntity serviceEntity = new SiteClientsServiceMappingEntity();
                            serviceEntity.Create();
                            serviceEntity.F_ClientId = client.F_Id;
                            serviceEntity.F_ServiceId = clientEntity.F_Id;
                            db.Insert<SiteClientsServiceMappingEntity>(serviceEntity);
                            //操作记录
                            SysOperationLogEntity operation1 = new SysOperationLogEntity();
                            operation1.Create();
                            operation1.F_Flag = 1;
                            operation1.F_Entity = "SiteClientsServiceMappingEntity";
                            operation1.F_Context = serviceEntity.ToJson();
                            db.Insert<SysOperationLogEntity>(operation1);

                            List<SiteClientsEntity> clientList = CacheFactory.Cache().Get("KHXX") as List<SiteClientsEntity>;
                            if (clientList == null)
                            {
                                clientList = new List<SiteClientsEntity>();
                            }
                            clientList.Add(client);
                            CacheFactory.Cache().Insert("KHXX", clientList);
                        }
                        else
                        {
                            if(entity.F_MappingId != null)
                            {
                                client.F_ClientName = entity.F_MappingName;
                                db.Update<SiteClientsEntity>(client);

                                //操作记录
                                SysOperationLogEntity operation1 = new SysOperationLogEntity();
                                operation1.Create();
                                operation1.F_Flag = 2;
                                operation1.F_Entity = "SiteClientsEntity";
                                operation1.F_Context = client.ToJson();
                                db.Insert<SysOperationLogEntity>(operation1);
                            }                            
                            SiteClientsServiceMappingEntity serviceEntity2 = GetFindServiceMapping(entity.F_MappingId, clientEntity.F_Id);
                            if (serviceEntity2 == null && entity.F_MappingId!=null)
                            {
                                serviceEntity2 = new SiteClientsServiceMappingEntity();
                                serviceEntity2.Create();
                                serviceEntity2.F_ClientId = entity.F_MappingId;
                                serviceEntity2.F_ServiceId = clientEntity.F_Id;

                                db.Insert<SiteClientsServiceMappingEntity>(serviceEntity2);

                                //操作记录
                                SysOperationLogEntity operation1 = new SysOperationLogEntity();
                                operation1.Create();
                                operation1.F_Flag = 1;
                                operation1.F_Entity = "SiteClientsServiceMappingEntity";
                                operation1.F_Context = serviceEntity2.ToJson();
                                db.Insert<SysOperationLogEntity>(operation1);
                            }
                        }
                        
                    }
                    //品牌组信息
                    SiteClientsBrandsEntity brands = brandsRepository.FindEntity(entity.F_BrandId);
                    if (entity.F_BrandId != null || entity.F_BrandName!=null)
                    {
                        if (brands == null)
                        {
                            brands = new SiteClientsBrandsEntity();
                            brands.Create();
                            brands.F_ClientId = clientEntity.F_Id;
                            brands.F_BrandName = entity.F_BrandName;
                            db.Insert<SiteClientsBrandsEntity>(brands);
                            //操作记录
                            SysOperationLogEntity operation1 = new SysOperationLogEntity();
                            operation1.Create();
                            operation1.F_Flag = 1;
                            operation1.F_Entity = "SiteClientsBrandsEntity";
                            operation1.F_Context = brands.ToJson();
                            db.Insert<SysOperationLogEntity>(operation1);

                            List<SiteClientsBrandsEntity> brandsList = CacheFactory.Cache().Get("PPXX") as List<SiteClientsBrandsEntity>;
                            if (brandsList == null)
                            {
                                brandsList = new List<SiteClientsBrandsEntity>();
                            }
                            brandsList.Add(brands);
                            CacheFactory.Cache().Insert("PPXX", brandsList);

                            SiteClientsBrandsMappingEntity brandsMapping = new SiteClientsBrandsMappingEntity();
                            brandsMapping.Create();
                            brandsMapping.F_DemandId = demandEntity.F_Id;
                            brandsMapping.F_BrandId = brands.F_Id;
                            db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping);
                            //操作记录
                            SysOperationLogEntity operation2 = new SysOperationLogEntity();
                            operation2.Create();
                            operation2.F_Flag = 1;
                            operation2.F_Entity = "SiteClientsBrandsMappingEntity";
                            operation2.F_Context = brandsMapping.ToJson();
                            db.Insert<SysOperationLogEntity>(operation2);
                        }
                        else
                        {
                            brands.F_BrandName = entity.F_BrandName;
                            db.Update<SiteClientsBrandsEntity>(brands);
                            //操作记录
                            SysOperationLogEntity operation6 = new SysOperationLogEntity();
                            operation6.Create();
                            operation6.F_Flag = 1;
                            operation6.F_Entity = "SiteClientsBrandsEntity";
                            operation6.F_Context = brands.ToJson();
                            db.Insert<SysOperationLogEntity>(operation6);

                            SiteClientsBrandsMappingEntity brandsMapping2 = GetFindBrandsMappingEntity(entity.F_BrandId, demandEntity.F_Id);
                            if (brandsMapping2 == null)
                            {
                                brandsMapping2 = new SiteClientsBrandsMappingEntity();
                                brandsMapping2.Create();
                                brandsMapping2.F_DemandId = demandEntity.F_Id;
                                brandsMapping2.F_BrandId = brands.F_Id;
                                db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping2);

                                //操作记录
                                SysOperationLogEntity operation1 = new SysOperationLogEntity();
                                operation1.Create();
                                operation1.F_Flag = 1;
                                operation1.F_Entity = "SiteClientsBrandsMappingEntity";
                                operation1.F_Context = brandsMapping2.ToJson();
                                db.Insert<SysOperationLogEntity>(operation1);
                            }
                        }
                        
                    }

                    //项目组信息
                    SiteClientsAllProjectsEntity projects = projectsRepository.FindEntity(entity.F_ProjectId);
                    if (entity.F_ProjectId != null || entity.F_ProjectName!=null)
                    {
                        if (projects == null)
                        {
                            projects = new SiteClientsAllProjectsEntity();
                            projects.Create();
                            projects.F_ClientId = clientEntity.F_Id;
                            projects.F_ProjectName = entity.F_ProjectName;
                            db.Insert<SiteClientsAllProjectsEntity>(projects);

                            //操作记录
                            SysOperationLogEntity operation5 = new SysOperationLogEntity();
                            operation5.Create();
                            operation5.F_Flag = 1;
                            operation5.F_Entity = "SiteClientsAllProjectsEntity";
                            operation5.F_Context = projects.ToJson();
                            db.Insert<SysOperationLogEntity>(operation5);

                            List<SiteClientsAllProjectsEntity> projectsList = CacheFactory.Cache().Get("XMZXX") as List<SiteClientsAllProjectsEntity>;
                            if (projectsList == null)
                            {
                                projectsList = new List<SiteClientsAllProjectsEntity>();
                            }
                            projectsList.Add(projects);
                            CacheFactory.Cache().Insert("XMZXX", projectsList);

                            SiteClientsAllProjectsMappingEntity projectsMapping = new SiteClientsAllProjectsMappingEntity();
                            projectsMapping.Create();
                            projectsMapping.F_ProjectId = projects.F_Id;
                            projectsMapping.F_DemandId = demandEntity.F_Id;
                            db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping);

                            //操作记录
                            SysOperationLogEntity operation1 = new SysOperationLogEntity();
                            operation1.Create();
                            operation1.F_Flag = 1;
                            operation1.F_Entity = "SiteClientsAllProjectsMappingEntity";
                            operation1.F_Context = projectsMapping.ToJson();
                            db.Insert<SysOperationLogEntity>(operation1);
                        }
                        else
                        {
                            projects.F_ProjectName = entity.F_ProjectName;
                            db.Update<SiteClientsAllProjectsEntity>(projects);
                            //操作记录
                            SysOperationLogEntity operation1 = new SysOperationLogEntity();
                            operation1.Create();
                            operation1.F_Flag = 2;
                            operation1.F_Entity = "SiteClientsAllProjectsEntity";
                            operation1.F_Context = projects.ToJson();
                            db.Insert<SysOperationLogEntity>(operation1);

                            SiteClientsAllProjectsMappingEntity projectsMapping2 = GetSiteClientsAllProjectsMapping(projects.F_Id, demandEntity.F_Id);
                            if (projectsMapping2 == null)
                            {
                                projectsMapping2 = new SiteClientsAllProjectsMappingEntity();
                                projectsMapping2.Create();
                                projectsMapping2.F_ProjectId = projects.F_Id;
                                projectsMapping2.F_DemandId = demandEntity.F_Id;
                                db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping2);

                                //操作记录
                                SysOperationLogEntity operation2 = new SysOperationLogEntity();
                                operation2.Create();
                                operation2.F_Flag = 2;
                                operation2.F_Entity = "SiteClientsAllProjectsMappingEntity";
                                operation2.F_Context = projectsMapping2.ToJson();
                                db.Insert<SysOperationLogEntity>(operation2);
                            }
                        }
                        
                    }


                    ////联系人信息
                    SiteClientsProjectByContactEntity contacts = contactRepository.FindEntity(entity.F_ContactId);
                    if (entity.F_ContactId != null || entity.F_Contact!=null)
                    {
                        if (contacts == null)
                        {
                            contacts = new SiteClientsProjectByContactEntity();
                            contacts.Create();
                            contacts.F_Contact = entity.F_Contact;
                            contacts.F_DepartmentId = entity.F_DepartmentId;
                            contacts.F_PositionId = entity.F_PositionId;
                            contacts.F_Sex = entity.F_Sex;
                            contacts.F_Phone = entity.F_Phone;
                            contacts.F_Telephone = entity.F_Telephone;
                            contacts.F_Mail = entity.F_Mail;
                            contacts.F_ClientId = clientEntity.F_Id;
                            db.Insert<SiteClientsProjectByContactEntity>(contacts);

                            //操作记录
                            SysOperationLogEntity operation4 = new SysOperationLogEntity();
                            operation4.Create();
                            operation4.F_Flag = 1;
                            operation4.F_Entity = "SiteClientsProjectByContactEntity";
                            operation4.F_Context = contacts.ToJson();
                            db.Insert<SysOperationLogEntity>(operation4);

                            List<SiteClientsProjectByContactEntity> contactsList = CacheFactory.Cache().Get("LXRXX") as List<SiteClientsProjectByContactEntity>;
                            if (contactsList == null)
                            {
                                contactsList = new List<SiteClientsProjectByContactEntity>();
                            }
                            contactsList.Add(contacts);
                            CacheFactory.Cache().Insert("LXRXX", contacts);

                            SiteClientsContactMappingEntity contactMapping = new SiteClientsContactMappingEntity();
                            contactMapping.Create();
                            contactMapping.F_ContactId = contacts.F_Id;
                            contactMapping.F_DemandId = demandEntity.F_Id;
                            db.Insert<SiteClientsContactMappingEntity>(contactMapping);

                            //操作记录
                            SysOperationLogEntity operation1 = new SysOperationLogEntity();
                            operation1.Create();
                            operation1.F_Flag = 1;
                            operation1.F_Entity = "SiteClientsContactMappingEntity";
                            operation1.F_Context = contacts.ToJson();
                            db.Insert<SysOperationLogEntity>(operation1);
                        }
                        else
                        {                            
                            contacts.F_Contact = entity.F_Contact;
                            contacts.F_DepartmentId = entity.F_DepartmentId;
                            contacts.F_PositionId = entity.F_PositionId;
                            contacts.F_Sex = entity.F_Sex;
                            contacts.F_Phone = entity.F_Phone;
                            contacts.F_Telephone = entity.F_Telephone;
                            contacts.F_Mail = entity.F_Mail;
                            db.Update<SiteClientsProjectByContactEntity>(contacts);

                            //操作记录
                            SysOperationLogEntity operation3 = new SysOperationLogEntity();
                            operation3.Create();
                            operation3.F_Flag = 2;
                            operation3.F_Entity = "SiteClientsProjectByContactEntity";
                            operation3.F_Context = contacts.ToJson();
                            db.Insert<SysOperationLogEntity>(operation3);

                            SiteClientsContactMappingEntity contactMapping = GetSiteClientsContactMapping(contacts.F_Id, demandEntity.F_Id);
                            if (contactMapping == null)
                            {
                                contactMapping = new SiteClientsContactMappingEntity();
                                contactMapping.Create();
                                contactMapping.F_ContactId = contacts.F_Id;
                                contactMapping.F_DemandId = demandEntity.F_Id;
                                db.Insert<SiteClientsContactMappingEntity>(contactMapping);

                                //操作记录
                                SysOperationLogEntity operation1 = new SysOperationLogEntity();
                                operation1.Create();
                                operation1.F_Flag = 1;
                                operation1.F_Entity = "SiteClientsContactMappingEntity";
                                operation1.F_Context = contactMapping.ToJson();
                                db.Insert<SysOperationLogEntity>(operation1);
                            }
                        }
                    }
                    
                    order.CreateNo();
                    order.F_Id = autoApp.CreateNumber();
                    order.F_DemandId = demandEntity.F_Id;
                    order.F_OrderEnvironment = 1;
                    order.F_WorkFormId = "lc1001";
                    demandEntity.F_State = 0;
                    if (entity.F_Source == "1")
                    {
                        var LoginInfo = OperatorProvider.Provider.GetCurrent();
                        order.F_FlowUserId = LoginInfo.UserId;
                        if (contacts != null)
                        {
                            order.F_OrderState = 1;
                            // 1:场地推荐(场地档期审核) 初始化为 等待跟进
                            order.F_OrderStateProcess = -1;
                            demandEntity.F_State = 1;
                        }
                        order.F_State = 1;
                    }
                    else
                    {
                        order.F_OrderState = 0;
                        order.F_OrderStateProcess = 0;
                        if (contacts != null)
                        {
                            order.F_State = 1;
                            demandEntity.F_State = 1;
                        }
                        else
                        {
                            order.F_State = 2;
                            demandEntity.F_State = 0;
                        }
                    }

                    db.Insert<SiteClientsProjectByDemandEntity>(demandEntity);
                    //操作记录
                    SysOperationLogEntity operation = new SysOperationLogEntity();
                    operation.Create();
                    operation.F_Flag = 1;
                    operation.F_Entity = "SiteClientsProjectByDemandEntity";
                    operation.F_Context = demandEntity.ToJson();
                    db.Insert<SysOperationLogEntity>(operation);

                    db.Insert<ClientOrderEntity>(order);
                    //操作记录
                    SysOperationLogEntity operation11 = new SysOperationLogEntity();
                    operation11.Create();
                    operation11.F_Flag = 1;
                    operation11.F_Entity = "ClientOrderEntity";
                    operation11.F_Context = order.ToJson();
                    db.Insert<SysOperationLogEntity>(operation);

                    returnEntity.F_DemandId = demandEntity.F_Id;
                    returnEntity.F_OrderId = order.F_Id;
                    returnEntity.F_OrderState = order.F_OrderState;
                }
                db.Commit();
                
            }
            return returnEntity;
        }

        public void SubmitProjectData(ClientProjectAddActionModel entity)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                // 需求信息
                SiteClientsProjectByDemandEntity demandEntity = new SiteClientsProjectByDemandEntity();
                demandEntity.Create();
                demandEntity.F_Source = entity.F_Source;
                demandEntity.F_ActivityTheme = entity.F_ActivityTheme;
                demandEntity.F_ActivityType = entity.F_ActivityType;
                demandEntity.F_DemandCash = entity.F_DemandCash;
                demandEntity.F_ActivityStartDate = entity.F_ActivityStartDate;

                demandEntity.F_ActivityEndDate = entity.F_ActivityEndDate;
                demandEntity.F_ActivityCityId = entity.F_ActivityCityId;
                demandEntity.F_SiteType = entity.F_SiteType;
                demandEntity.F_SiteArea = entity.F_SiteArea;
                demandEntity.F_Height = entity.F_Height;

                demandEntity.F_PersionNumber = entity.F_PersionNumber;
                demandEntity.F_Note = entity.F_Note;

                demandEntity.F_ClientId = entity.F_ClientId;
                demandEntity.F_State = 0;
                demandEntity.F_BuildDate = entity.F_BuildDate;
                demandEntity.F_IndustryId = entity.F_ZkIndustryId;

                //检索直客信息
                if (entity.F_ClientType == "2")
                {
                    SiteClientsEntity client = clientRepository.FindEntity(entity.F_MappingId);
                    if (client == null && entity.F_MappingId!=null)
                    {
                        client = new SiteClientsEntity();
                        client.Create();
                        client.F_ClientName = entity.F_MappingId;                        
                        db.Insert<SiteClientsEntity>(client);
                        //操作记录
                        SysOperationLogEntity operation = new SysOperationLogEntity();
                        operation.Create();
                        operation.F_Flag = 1;
                        operation.F_Entity = "SiteClientsEntity";
                        operation.F_Context = client.ToJson();
                        db.Insert<SysOperationLogEntity>(operation);

                        SiteClientsServiceMappingEntity serviceEntity = new SiteClientsServiceMappingEntity();
                        serviceEntity.Create();
                        serviceEntity.F_ClientId = client.F_Id;
                        serviceEntity.F_ServiceId = entity.F_MappingId;
                        db.Insert<SiteClientsServiceMappingEntity>(serviceEntity);
                        //操作记录
                        SysOperationLogEntity operation1 = new SysOperationLogEntity();
                        operation1.Create();
                        operation1.F_Flag = 1;
                        operation1.F_Entity = "SiteClientsServiceMappingEntity";
                        operation1.F_Context = serviceEntity.ToJson();
                        db.Insert<SysOperationLogEntity>(operation1);

                        List<SiteClientsEntity> clientList = CacheFactory.Cache().Get("KHXX") as List<SiteClientsEntity>;
                        if (clientList == null)
                        {
                            clientList = new List<SiteClientsEntity>();
                        }
                        clientList.Add(client);
                        CacheFactory.Cache().Insert("KHXX", clientList);
                    }
                    else
                    {
                        SiteClientsServiceMappingEntity serviceEntity = GetFindServiceMapping(entity.F_MappingId, entity.F_ClientId);
                        if (serviceEntity == null && entity.F_MappingId!=null)
                        {
                            serviceEntity = new SiteClientsServiceMappingEntity();
                            serviceEntity.Create();
                            serviceEntity.F_ClientId = entity.F_MappingId;
                            serviceEntity.F_ServiceId = entity.F_ClientId;
                            db.Insert<SiteClientsServiceMappingEntity>(serviceEntity);

                            //操作记录
                            SysOperationLogEntity operation = new SysOperationLogEntity();
                            operation.Create();
                            operation.F_Flag = 1;
                            operation.F_Entity = "SiteClientsServiceMappingEntity";
                            operation.F_Context = serviceEntity.ToJson();
                            db.Insert<SysOperationLogEntity>(operation);
                        }
                    }
                }

                SiteClientsBrandsEntity brands = brandsRepository.FindEntity(entity.F_BrandId);
                if (entity.F_BrandId != null)
                {
                    //品牌组信息                    
                    if (brands == null)
                    {
                        brands = new SiteClientsBrandsEntity();
                        brands.Create();
                        brands.F_ClientId = entity.F_ClientId;
                        brands.F_BrandName = entity.F_BrandId;
                        db.Insert<SiteClientsBrandsEntity>(brands);

                        //操作记录
                        SysOperationLogEntity operation = new SysOperationLogEntity();
                        operation.Create();
                        operation.F_Flag = 1;
                        operation.F_Entity = "SiteClientsBrandsEntity";
                        operation.F_Context = brands.ToJson();
                        db.Insert<SysOperationLogEntity>(operation);

                        List<SiteClientsBrandsEntity> brandsList = CacheFactory.Cache().Get("PPXX") as List<SiteClientsBrandsEntity>;
                        if (brandsList == null)
                        {
                            brandsList = new List<SiteClientsBrandsEntity>();
                        }
                        brandsList.Add(brands);
                        CacheFactory.Cache().Insert("PPXX", brandsList);

                        SiteClientsBrandsMappingEntity brandsMapping = new SiteClientsBrandsMappingEntity();
                        brandsMapping.Create();
                        brandsMapping.F_DemandId = demandEntity.F_Id;
                        brandsMapping.F_BrandId = brands.F_Id;
                        db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping);

                        //操作记录
                        SysOperationLogEntity operation1 = new SysOperationLogEntity();
                        operation1.Create();
                        operation1.F_Flag = 1;
                        operation1.F_Entity = "SiteClientsBrandsMappingEntity";
                        operation1.F_Context = brandsMapping.ToJson();
                        db.Insert<SysOperationLogEntity>(operation);
                    }
                    else
                    {
                        SiteClientsBrandsMappingEntity brandsMapping = GetFindBrandsMappingEntity(entity.F_BrandId, demandEntity.F_Id);
                        if (brandsMapping == null)
                        {
                            brandsMapping = new SiteClientsBrandsMappingEntity();
                            brandsMapping.Create();
                            brandsMapping.F_DemandId = demandEntity.F_Id;
                            brandsMapping.F_BrandId = brands.F_Id;
                            db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping);

                            //操作记录
                            SysOperationLogEntity operation = new SysOperationLogEntity();
                            operation.Create();
                            operation.F_Flag = 1;
                            operation.F_Entity = "SiteClientsBrandsMappingEntity";
                            operation.F_Context = brandsMapping.ToJson();
                            db.Insert<SysOperationLogEntity>(operation);
                        }
                    }
                }

                //项目组信息
                SiteClientsAllProjectsEntity projects = projectsRepository.FindEntity(entity.F_ProjectId);
                if (entity.F_ProjectId != null)
                {
                    if (projects == null)
                    {
                        projects = new SiteClientsAllProjectsEntity();
                        projects.Create();
                        projects.F_ClientId = entity.F_ClientId;
                        projects.F_ProjectName = entity.F_ProjectId;
                        db.Insert<SiteClientsAllProjectsEntity>(projects);
                        //操作记录
                        SysOperationLogEntity operation = new SysOperationLogEntity();
                        operation.Create();
                        operation.F_Flag = 1;
                        operation.F_Entity = "SiteClientsAllProjectsEntity";
                        operation.F_Context = projects.ToJson();
                        db.Insert<SysOperationLogEntity>(operation);


                        List<SiteClientsAllProjectsEntity> projectsList = CacheFactory.Cache().Get("XMZXX") as List<SiteClientsAllProjectsEntity>;
                        if (projectsList == null)
                        {
                            projectsList = new List<SiteClientsAllProjectsEntity>();
                        }
                        projectsList.Add(projects);
                        CacheFactory.Cache().Insert("XMZXX", projectsList);

                        SiteClientsAllProjectsMappingEntity projectsMapping = new SiteClientsAllProjectsMappingEntity();
                        projectsMapping.Create();
                        projectsMapping.F_ProjectId = projects.F_Id;
                        projectsMapping.F_DemandId = demandEntity.F_Id;
                        db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping);

                        //操作记录
                        SysOperationLogEntity operation1 = new SysOperationLogEntity();
                        operation1.Create();
                        operation1.F_Flag = 1;
                        operation1.F_Entity = "SiteClientsAllProjectsMappingEntity";
                        operation1.F_Context = projectsMapping.ToJson();
                        db.Insert<SysOperationLogEntity>(operation1);
                    }
                    else
                    {
                        SiteClientsAllProjectsMappingEntity projectsMapping = GetSiteClientsAllProjectsMapping(projects.F_Id, demandEntity.F_Id);
                        if (projectsMapping == null)
                        {
                            projectsMapping = new SiteClientsAllProjectsMappingEntity();
                            projectsMapping.Create();
                            projectsMapping.F_ProjectId = projects.F_Id;
                            projectsMapping.F_DemandId = demandEntity.F_Id;
                            db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping);
                            //操作记录
                            SysOperationLogEntity operation = new SysOperationLogEntity();
                            operation.Create();
                            operation.F_Flag = 1;
                            operation.F_Entity = "SiteClientsAllProjectsMappingEntity";
                            operation.F_Context = projects.ToJson();
                            db.Insert<SysOperationLogEntity>(operation);
                        }
                    }
                }

                ////联系人信息
                SiteClientsProjectByContactEntity contacts = contactRepository.FindEntity(entity.F_ContactId);
                if (entity.F_ContactId != null)
                {
                    if (contacts == null)
                    {
                        contacts = new SiteClientsProjectByContactEntity();
                        contacts.Create();
                        contacts.F_Contact = entity.F_ContactId;
                        contacts.F_DepartmentId = entity.F_DepartmentId;
                        contacts.F_PositionId = entity.F_PositionId;
                        contacts.F_Sex = entity.F_Sex;
                        contacts.F_Phone = entity.F_Phone;
                        contacts.F_Telephone = entity.F_Telephone;
                        contacts.F_Mail = entity.F_Mail;
                        contacts.F_ClientId = entity.F_ClientId;
                        db.Insert<SiteClientsProjectByContactEntity>(contacts);
                        //操作记录
                        SysOperationLogEntity operation = new SysOperationLogEntity();
                        operation.Create();
                        operation.F_Flag = 1;
                        operation.F_Entity = "SiteClientsProjectByContactEntity";
                        operation.F_Context = contacts.ToJson();
                        db.Insert<SysOperationLogEntity>(operation);

                        List<SiteClientsProjectByContactEntity> contactsList = CacheFactory.Cache().Get("LXRXX") as List<SiteClientsProjectByContactEntity>;
                        if (contactsList == null)
                        {
                            contactsList = new List<SiteClientsProjectByContactEntity>();
                        }
                        contactsList.Add(contacts);
                        CacheFactory.Cache().Insert("LXRXX", contacts);

                        SiteClientsContactMappingEntity contactMapping = new SiteClientsContactMappingEntity();
                        contactMapping.Create();
                        contactMapping.F_ContactId = contacts.F_Id;
                        contactMapping.F_DemandId = demandEntity.F_Id;
                        db.Insert<SiteClientsContactMappingEntity>(contactMapping);
                    }
                    else
                    {
                        contacts.F_Contact = contacts.F_Contact;
                        contacts.F_DepartmentId = entity.F_DepartmentId;
                        contacts.F_PositionId = entity.F_PositionId;
                        contacts.F_Sex = entity.F_Sex;
                        contacts.F_Phone = entity.F_Phone;
                        contacts.F_Telephone = entity.F_Telephone;
                        contacts.F_Mail = entity.F_Mail;
                        db.Update<SiteClientsProjectByContactEntity>(contacts);

                        //操作记录
                        SysOperationLogEntity operation = new SysOperationLogEntity();
                        operation.Create();
                        operation.F_Flag = 2;
                        operation.F_Entity = "SiteClientsProjectByContactEntity";
                        operation.F_Context = contacts.ToJson();
                        db.Insert<SysOperationLogEntity>(operation);

                        SiteClientsContactMappingEntity contactMapping = GetSiteClientsContactMapping(contacts.F_Id, demandEntity.F_Id);
                        if (contactMapping == null)
                        {
                            contactMapping = new SiteClientsContactMappingEntity();
                            contactMapping.Create();
                            contactMapping.F_ContactId = contacts.F_Id;
                            contactMapping.F_DemandId = demandEntity.F_Id;
                            db.Insert<SiteClientsContactMappingEntity>(contactMapping);
                        }
                    }
                }


                ClientOrderEntity order = new ClientOrderEntity();
                order.CreateNo();
                order.F_Id = autoApp.CreateNumber();
                order.F_DemandId = demandEntity.F_Id;
                order.F_OrderEnvironment = 1;
                order.F_WorkFormId = "lc1001";
                if (entity.F_Source == "1")
                {
                    var LoginInfo = OperatorProvider.Provider.GetCurrent();
                    order.F_FlowUserId = LoginInfo.UserId;
                    if (contacts != null)
                    {
                        order.F_OrderState = 1;
                        order.F_OrderStateProcess = 0;
                        demandEntity.F_State = 1;
                    }
                    order.F_State = 1;
                }
                else
                {
                    order.F_OrderState = 0;
                    order.F_OrderStateProcess = 0;
                    if (contacts != null)
                    {
                        order.F_State = 1;
                        demandEntity.F_State = 1;
                    }
                    else
                    {
                        order.F_State = 2;
                        demandEntity.F_State = 0;
                    }
                }
                db.Insert<ClientOrderEntity>(order);
                db.Insert<SiteClientsProjectByDemandEntity>(demandEntity);
                db.Commit();
            }            
        }

        /// <summary>
        /// 提交需求信息
        /// </summary>
        /// <param name="entity"></param>
        public void SubmitDemandData(ClientDemandActionModel entity)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientsProjectByDemandEntity demandEntity = new SiteClientsProjectByDemandEntity();
                // 需求信息
                demandEntity.Create();
                demandEntity.F_Source = entity.F_Source;
                demandEntity.F_ActivityTheme = entity.F_ActivityTheme;
                demandEntity.F_ActivityType = entity.F_ActivityType;
                demandEntity.F_DemandCash = entity.F_DemandCash;
                demandEntity.F_ActivityStartDate = entity.F_ActivityStartDate;
                demandEntity.F_ActivityEndDate = entity.F_ActivityEndDate;
                demandEntity.F_BuildDate = entity.F_BuildDate;
                demandEntity.F_ActivityCityId = entity.F_ActivityCityId;
                demandEntity.F_SiteType = entity.F_SiteType;
                demandEntity.F_SiteArea = entity.F_SiteArea;
                demandEntity.F_Height = entity.F_Height;
                demandEntity.F_Note = entity.F_Note;
                demandEntity.F_PersionNumber = entity.F_PersionNumber;
                demandEntity.F_ClientId = entity.F_ClientId;
                demandEntity.F_State = 1;
                demandEntity.F_IndustryId = entity.F_ZkIndustryId;
                demandEntity.F_Intention = entity.F_Intention;
                db.Insert<SiteClientsProjectByDemandEntity>(demandEntity);
                //品牌
                SiteClientsBrandsMappingEntity brandsMapping = new SiteClientsBrandsMappingEntity();
                brandsMapping.Create();
                brandsMapping.F_BrandId = entity.F_BrandId;
                brandsMapping.F_DemandId = demandEntity.F_Id;
                db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping);
                //项目组
                SiteClientsAllProjectsMappingEntity projectsMapping = new SiteClientsAllProjectsMappingEntity();
                projectsMapping.Create();
                projectsMapping.F_ProjectId = entity.F_ProjectId;
                projectsMapping.F_DemandId = demandEntity.F_Id;
                db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping);
                //联系人
                SiteClientsContactMappingEntity contactMapping = new SiteClientsContactMappingEntity();
                contactMapping.Create();
                contactMapping.F_ContactId = entity.F_ContactId;
                contactMapping.F_DemandId = demandEntity.F_Id;
                db.Insert<SiteClientsContactMappingEntity>(contactMapping);

                //订单数据
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                ClientOrderEntity orderEntity = new ClientOrderEntity();
                orderEntity.CreateNo();
                orderEntity.F_Id = autoApp.CreateNumber();
                orderEntity.F_DemandId = demandEntity.F_Id;
                if (entity.F_Source == "1")
                {
                    orderEntity.F_FlowUserId = LoginInfo.UserId;
                    orderEntity.F_OrderState = 1;
                }
                else
                {
                    orderEntity.F_OrderState = 0;
                }
                orderEntity.F_OrderStateProcess = -1;
                orderEntity.F_State = 1;
                orderEntity.F_OrderEnvironment = 1;
                orderEntity.F_WorkFormId = "lc1001";
                db.Insert<ClientOrderEntity>(orderEntity);
                db.Commit();
            }
        }

        /// <summary>
        /// 通过项目组编号、联系人、联系电话获取其信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="contract"></param>
        /// <param name="phone"></param>
        /// <returns></returns>
        public SiteClientsProjectByContactEntity GetContactEntity(string projectId, string contract, string phone)
        {
            var result = new SiteClientsProjectByContactEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Clients_ProjectByContact where F_ProjectId=@projectId and F_Contact=@contract and F_Phone=@phone";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@projectId", projectId),
                    new MySqlParameter("@contract", contract),
                    new MySqlParameter("@phone", phone),
                };
                result = db.FindList<SiteClientsProjectByContactEntity>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public string SubmitCompanyInfos(SiteClientsEntity entity, string keyValue)
        {
            string F_Id = "";
            if (string.IsNullOrEmpty(keyValue))
            {
                entity.Create();
                clientRepository.Insert(entity);
                F_Id = entity.F_Id;
            }
            else
            {
                entity.Modify(keyValue);
                clientRepository.Update(entity);
                F_Id = keyValue;
            }
            return F_Id;
        }

        public ClientOrderEntity SubmitProjectForm(ClientProjectUpdateActionModel entity)
        {
            ClientOrderEntity order = null;
            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientsProjectByDemandEntity demandEntity = demandRepository.FindEntity(entity.DemandId);
                // 需求信息                 
                demandEntity.F_ActivityTheme = entity.F_ActivityTheme;
                demandEntity.F_ActivityType = entity.F_ActivityType;
                demandEntity.F_DemandCash = entity.F_DemandCash;
                demandEntity.F_ActivityStartDate = entity.F_ActivityStartDate;
                demandEntity.F_ActivityEndDate = entity.F_ActivityEndDate;
                demandEntity.F_BuildDate = entity.F_BuildDate;
                demandEntity.F_ActivityCityId = entity.F_ActivityCityId;
                demandEntity.F_SiteType = entity.F_SiteType;
                demandEntity.F_SiteArea = entity.F_SiteArea;
                demandEntity.F_Note = entity.F_Note;
                demandEntity.F_Height = entity.F_Height;
                demandEntity.F_PersionNumber = entity.F_PersionNumber;
                demandEntity.F_Source = entity.F_Source;
                demandEntity.F_IndustryId = entity.F_ZkIndustryId;
                demandEntity.F_Intention = entity.F_Intention;

                // 直客
                SiteClientsEntity mappingClient = clientRepository.FindEntity(entity.F_MappingId);
                if (mappingClient == null && entity.F_MappingId!=null)
                {
                    mappingClient = new SiteClientsEntity();
                    mappingClient.Create();
                    mappingClient.F_ClientName = entity.MappingName;                    
                    db.Insert<SiteClientsEntity>(mappingClient);

                    SiteClientsServiceMappingEntity mapping = new SiteClientsServiceMappingEntity();
                    mapping.Create();
                    mapping.F_ClientId = mappingClient.F_Id;
                    mapping.F_ServiceId = demandEntity.F_ClientId;
                    db.Insert<SiteClientsServiceMappingEntity>(mapping);
                }
                else
                {
                    if(entity.F_MappingId != null)
                    {
                        mappingClient.F_ClientName = entity.MappingName;
                        db.Update<SiteClientsEntity>(mappingClient);
                    }                    
                    SiteClientsServiceMappingEntity mapping2 = GetFindServiceMapping(entity.F_MappingId, demandEntity.F_ClientId);
                    if (mapping2 == null && entity.F_MappingId!=null)
                    {
                        mapping2 = new SiteClientsServiceMappingEntity();
                        mapping2.Create();
                        mapping2.F_ClientId = mappingClient.F_Id;
                        mapping2.F_ServiceId = demandEntity.F_ClientId;
                        db.Insert<SiteClientsServiceMappingEntity>(mapping2);
                    }
                }
                

                SiteClientsBrandsEntity brands = brandsRepository.FindEntity(entity.F_BrandId);
                if (entity.F_BrandId != null)
                {
                    //品牌组信息                    
                    if (brands == null)
                    {
                        brands = new SiteClientsBrandsEntity();
                        brands.Create();
                        brands.F_ClientId = entity.F_ClientId;
                        brands.F_BrandName = entity.F_BrandId;
                        db.Insert<SiteClientsBrandsEntity>(brands);
                        List<SiteClientsBrandsEntity> brandsList = CacheFactory.Cache().Get("PPXX") as List<SiteClientsBrandsEntity>;
                        if (brandsList == null)
                        {
                            brandsList = new List<SiteClientsBrandsEntity>();
                        }
                        brandsList.Add(brands);
                        CacheFactory.Cache().Insert("PPXX", brandsList);

                        SiteClientsBrandsMappingEntity brandsMapping = new SiteClientsBrandsMappingEntity();
                        brandsMapping.Create();
                        brandsMapping.F_DemandId = demandEntity.F_Id;
                        brandsMapping.F_BrandId = brands.F_Id;
                        db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping);
                    }
                    else
                    {
                        brands.F_BrandName = entity.F_BrandName;
                        db.Update<SiteClientsBrandsEntity>(brands);
                        SiteClientsBrandsMappingEntity brandsMapping2 = GetFindBrandsMappingEntity(entity.F_BrandId, demandEntity.F_Id);
                        if (brandsMapping2 == null)
                        {
                            brandsMapping2 = new SiteClientsBrandsMappingEntity();
                            brandsMapping2.Create();
                            brandsMapping2.F_DemandId = demandEntity.F_Id;
                            brandsMapping2.F_BrandId = brands.F_Id;
                            db.Insert<SiteClientsBrandsMappingEntity>(brandsMapping2);
                        }
                    }
                    
                }

                //项目组信息
                SiteClientsAllProjectsEntity projects = projectsRepository.FindEntity(entity.F_ProjectId);
                if (entity.F_ProjectId != null)
                {
                    if (projects == null)
                    {
                        projects = new SiteClientsAllProjectsEntity();
                        projects.Create();
                        projects.F_ClientId = entity.F_ClientId;
                        projects.F_ProjectName = entity.F_ProjectId;
                        db.Insert<SiteClientsAllProjectsEntity>(projects);
                        List<SiteClientsAllProjectsEntity> projectsList = CacheFactory.Cache().Get("XMZXX") as List<SiteClientsAllProjectsEntity>;
                        if (projectsList == null)
                        {
                            projectsList = new List<SiteClientsAllProjectsEntity>();
                        }
                        projectsList.Add(projects);
                        CacheFactory.Cache().Insert("XMZXX", projectsList);

                        SiteClientsAllProjectsMappingEntity projectsMapping = new SiteClientsAllProjectsMappingEntity();
                        projectsMapping.Create();
                        projectsMapping.F_ProjectId = projects.F_Id;
                        projectsMapping.F_DemandId = demandEntity.F_Id;
                        db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping);
                    }
                    else
                    {
                        projects.F_ProjectName = entity.F_ProjectName;
                        db.Update<SiteClientsAllProjectsEntity>(projects);
                        SiteClientsAllProjectsMappingEntity projectsMapping2 = GetSiteClientsAllProjectsMapping(projects.F_Id, demandEntity.F_Id);
                        if (projectsMapping2 == null)
                        {
                            projectsMapping2 = new SiteClientsAllProjectsMappingEntity();
                            projectsMapping2.Create();
                            projectsMapping2.F_ProjectId = projects.F_Id;
                            projectsMapping2.F_DemandId = demandEntity.F_Id;
                            db.Insert<SiteClientsAllProjectsMappingEntity>(projectsMapping2);
                        }
                    }
                }

                //修改项目组信息
                SiteClientsProjectByContactEntity contactEntity = contactRepository.FindEntity(entity.contactId);
                if (contactEntity == null)
                {
                    contactEntity = new SiteClientsProjectByContactEntity();
                    contactEntity.Create();
                    contactEntity.F_Contact = entity.F_Contact;
                    contactEntity.F_DepartmentId = entity.F_DepartmentId;
                    contactEntity.F_PositionId = entity.F_PositionId;
                    contactEntity.F_Sex = entity.F_Sex;
                    contactEntity.F_Phone = entity.F_Phone;
                    contactEntity.F_Telephone = entity.F_Telephone;
                    contactEntity.F_Mail = entity.F_Mail;
                    contactEntity.F_ClientId = demandEntity.F_ClientId;
                    db.Insert<SiteClientsProjectByContactEntity>(contactEntity);

                    List<SiteClientsProjectByContactEntity> contactsList = CacheFactory.Cache().Get("LXRXX") as List<SiteClientsProjectByContactEntity>;
                    if (contactsList == null)
                    {
                        contactsList = new List<SiteClientsProjectByContactEntity>();
                    }
                    contactsList.Add(contactEntity);
                    CacheFactory.Cache().Insert("LXRXX", contactEntity);

                    SiteClientsContactMappingEntity contactMapping = new SiteClientsContactMappingEntity();
                    contactMapping.Create();
                    contactMapping.F_ContactId = contactEntity.F_Id;
                    contactMapping.F_DemandId = demandEntity.F_Id;
                    db.Insert<SiteClientsContactMappingEntity>(contactMapping);
                }
                else
                {
                    contactEntity.F_Contact = entity.F_Contact;
                    contactEntity.F_DepartmentId = entity.F_DepartmentId;
                    contactEntity.F_PositionId = entity.F_PositionId;
                    contactEntity.F_Sex = entity.F_Sex;
                    contactEntity.F_Phone = entity.F_Phone;
                    contactEntity.F_Telephone = entity.F_Telephone;
                    contactEntity.F_Mail = entity.F_Mail;
                    db.Update<SiteClientsProjectByContactEntity>(contactEntity);
                }
                if (contactEntity != null)
                {
                    var LoginInfo = OperatorProvider.Provider.GetCurrent();
                    order = GetOrderEntity(entity.DemandId);
                    if (order == null) {
                        order = new ClientOrderEntity();
                        order.CreateNo();
                        order.F_Id = autoApp.CreateNumber();
                        order.F_WorkFormId = "lc1001";
                        order.F_State = 1;
                        order.F_OrderEnvironment = 1;
                        order.F_DemandId = entity.DemandId;
                        if (demandEntity.F_Source == "1")
                        {
                            // 1:场地推荐(场地档期审核) 初始化为 -1 等待跟进
                            order.F_OrderState = 1;
                            order.F_OrderStateProcess = -1;
                            order.F_FlowUserId = demandEntity.F_CreatorUserId;
                        }
                        else
                        {
                            // 0:待指派初始化为 0 等待确认
                            order.F_OrderState = 0;
                            order.F_OrderStateProcess = 0;
                        }
                        db.Insert<ClientOrderEntity>(order);
                    }
                    else
                    {
                        order.F_WorkFormId = "lc1001";
                        order.F_State = 1;
                        order.F_OrderEnvironment = 1;
                        if (demandEntity.F_Source == "1")
                        {
                            // 1:场地推荐(场地档期审核) 初始化为 -1 等待跟进
                            if (order.F_FlowUserId == null)
                            {
                                order.F_OrderState = 1;
                                order.F_OrderStateProcess = -1;
                                order.F_FlowUserId = demandEntity.F_CreatorUserId;
                            }
                        }
                        else
                        {
                            if(order.F_FlowUserId==null)
                            {
                                // 0:待指派初始化为 0 等待确认
                                order.F_OrderState = 0;
                                order.F_OrderStateProcess = 0;
                            }                            
                        }
                        db.Update<ClientOrderEntity>(order);
                    }
                    
                    demandEntity.F_State = 1;
                }
                db.Update<SiteClientsProjectByDemandEntity>(demandEntity);
                db.Commit();
            }
            return order;
        }

        public ClientOrderEntity GetOrderEntity(string F_DemandId)
        {
            var result = new ClientOrderEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Client_Order a where a.F_DemandId=@F_DemandId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_DemandId", F_DemandId),
                };
                result = db.FindList<ClientOrderEntity>(strSql, parameter).FirstOrDefault();
            }
            return result;
        }

        public void SubmitCompanyForm(ClientCompanyActionModel entity)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientsEntity client = clientRepository.FindEntity(entity.F_ClientId);
                client.F_ClientType = entity.F_ClientType;
                client.F_ClientName = entity.F_ClientName;
                client.F_CompanyType = entity.F_CompanyType;
                client.F_ClientLevel = entity.F_ClientLevel;
                client.F_CityId = entity.F_CityId;
                client.F_AreaId = entity.F_AreaId;
                client.F_Address = entity.F_Address;
                client.F_IndustryId = entity.F_IndustryId;
                db.Update<SiteClientsEntity>(client);
                db.Commit();
            }
        }

        /// <summary>
        /// 更新订单推荐状态
        /// </summary>
        /// <param name="state"></param>
        /// <param name="keyValue"></param>
        public void UpdateOrderRecommendState(int state, string keyValue)
        {
            var entity = clientOrderrecommendRepository.FindEntity(x => x.F_Id == keyValue);
            entity.F_State = state;
            entity.Modify(keyValue);

            clientOrderrecommendRepository.Update(entity);
        }

        /// <summary>
        /// 获取我的审核信息列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<MyAuditViewModel> GetMyAuditList(Pagination pagination, string orderId)
        {
            var vms = clientOrderrecommendRepository.GetFlowManagerViewModelList(pagination, orderId);

            for (var i = 0; i < vms.Count; i++)
            {
                var vm = vms[i];

                switch (vm.F_ScheduleState)
                {
                    case "0":
                        vm.F_ScheduleState = "未审核";
                        break;
                    case "1":
                        vm.F_ScheduleState = "有档期";
                        break;
                    case "2":
                        vm.F_ScheduleState = "无档期";
                        break;
                }
            }

            return vms;
        }
    }
}
